import axios from 'axios'
import qs from 'qs'
const validateStatus = status => {
  return status >= 200 && status < 300
}
const apiBaseUrl =
  process.env.NODE_ENV === 'production' ? window.baseUrl : '/apis'

import { Toast } from 'vant'

// 创建时自定义默认配置，超时设置为全局默认值0秒
let axiosNew = axios.create({
  baseURL: apiBaseUrl,
  timeout: 6000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'x-requested-with': 'XMLHttpRequest'
  },
  validateStatus: validateStatus
})

let axiosPromiseArr = []
// http request 拦截器
axiosNew.interceptors.request.use(
  config => {
    // console.log('config====', config);
    // config.cancelToken = new axios.CancelToken(cancel => {
    //   axiosPromiseArr.push({
    //     cancel
    //   })
    // })

    const strSid = localStorage.getItem('strSid')
    const websvrpwd = 'suncnihold654321'
    if (config.method === 'post') {
      config.data = {
        strSid,
        websvrpwd,
        ...config.data
      }
    }
    config.data = qs.stringify(config.data)
    // const _strSid = '796f95f25e80486384ddd0f792632293';
    // config.headers.strSid = _strSid || ''
    // if (
    //   config.method === 'post' &&
    //   config.headers['Content-Type'] != 'multipart/form-data'
    // ) {
    //   config.data = qs.stringify(config.data)
    // }

    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http request 拦截器
axiosNew.interceptors.response.use(
  resp => {
    if (!resp.data || resp.data.constructor != Object) {
      Toast.fail('服务器异常')
      return Promise.reject('wrong')
    }
    if (resp.data.constructor == Object) {
      // resp.data.msg = resp.data.msg || '操作失败' + resp.data.code;

      let { code, msg } = resp.data
      if (!validateStatus(code) && code !== undefined) {
        Toast.fail(msg)
        //返回错误状态
        return Promise.reject(msg)
      }
      if (resp.data.globa_sessionTimeOut == -1) {
        Toast.fail(resp.data.tip)
      }
    }

    setTimeout(() => {
      Toast.clear()
    }, 1000)
    return resp?.data?.result
  },
  err => {
    if (err.toString().indexOf('timeout') != -1) {
      Toast.fail('请求超时')
      return Promise.reject('请求超时')
    }
    if (axiosPromiseArr.length) {
      Toast.fail('网络异常\n请稍后重试')
      return Promise.reject('网络异常\n请稍后重试')
    }
    axiosPromiseArr = []
  }
)
export default axiosNew
